<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>async的用法</title>
</head>
<body>
  
</body>

<script type="text/javascript">
  
  // async：将函数标记为异步函数，是Generator的一个语法糖
  // 作用：使得异步操作更加方便
  // 基本操作：
  // async：会返回一个Promise对象 then catch
  // await：等待命令，可加加不加，用在async命令中，如果async函数中有多个await，then函数会等待有的的await指令运行完后采取执行
  //        会自动转为Promise对象
  async function fn1() {
    let obj = {
      name: 'chengjunyu'
    }
    // return Promise.resolve(obj)
    console.log('await');
    return await obj.name
  }
  fn1().then(val => console.log(val)).catch(error => console.log(error))


  async function fn2() {
    // throw new Error('出错了')
    
    return Promise.reject('出错了')
    return Promise.resolve('hello')
    
  }
  fn2().then(val => console.log(val)).catch(error => console.log(error))

  const getJSON = function (url) {
    return new Promise((resolvoe, reject) => {
      const xhr = new XMLHttpRequest()
      xhr.open('GET', url)
      xhr.onreadystatechange = handler;
      xhr.responseType = 'json'
      xhr.setRequestHeader('Accept', 'application/json')
      xhr.send()

      function handler() {
        if (this.readyState === 4) {
          if (this.status === 200) {
            resolvoe(this.response.data)
          } else {
            reject(this.response.error)
          }
        }
        
      }
    })
  }

  async function getUser(url) {
    let res = await getJSON(url)
    console.log(res)
    return res
  }

  getUser('http://localhost:8001/user/get').then(res => console.log(res.age)).catch(err => console.log(err))
  console.log(123123);
  
</script>
</html>